/**
 * @description 产品管理
 * @author
 */

import React, { PureComponent } from 'react';
import { NoQueryC, TableC, PrimaryC, ModalC, AdvancedseriesProductId, DATA_ENTRY, FirstHeaderC, QuickQueryC, SecondHeaderC } from '../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import { connect } from 'dva';
import MyModal from './myModal';
import style from './index.less';
@Form.create()
@connect(({ ProductManageM, loading }) => ({
  ProductManageM,
  loading,
}))
export default class ProductManage extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      seriesProductId: undefined, //当前系列产品id
      isVisible: false, //模态窗是否弹出
      id: undefined, //编辑时的id
      record: {}, //编辑行的数据
      currentPage: 1, //页码
      numInPage: 10, //每页条数
      isNegativeCash: '0', //  0-全部，1-是负现金
    };
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.seriesProductId != this.props.seriesProductId) {
      let temp = this.props.seriesProductId;
      this.setState(
        {
          seriesProductId: nextProps.seriesProductId,
        },
        () => {
          if (temp) {
            this.getTableData(); //查询子产品信息列表 避免查询两次
          }
        },
      );
    }
  }
  componentWillUnmount() {
    //离开时清空model里的缓存数据
    this.props.dispatch({
      type: 'ProductManageM/save',
      payload: {
        tableData: { columns: [], dataSource: [] },
      },
    });
  }

  //获取表格数据
  getTableData = () => {
    const { dispatch } = this.props;
    const { seriesProductId, isNegativeCash } = this.state;
    if (!seriesProductId) return;
    const query = {
      seriesProductId,
      currentPage: 1,
      numInPage: 50000, //前端分页
      isNegativeCash,
    };
    dispatch({
      type: 'ProductManageM/getTableData',
      payload: query,
    });
  };
  // 点击确定
  handleOk = () => {
    const { isEdit, seriesProductId } = this.state;
    const { dispatch } = this.props;
    const data = this.child.getData();
    if (!data) return;
    const query = {
      listId: seriesProductId,
      ...data,
    };
    if (isEdit) query.id = this.state.id;
    const stTime = new Date(query.startDate); // 失效时间
    const edTime = new Date(query.endDate); // 生效时间
    if (query.startDate && stTime > edTime) {
      message.warning('到期日期不能早于起息日期');
    } else {
      dispatch({
        type: 'ProductManageM/addAndEdit',
        payload: query,
        callback: () => {
          this.getTableData();
          this.handleCancel(); //重置数据
        },
      });
    }
  };
  queryProductInfo = (id) => {
    //查询产品信息 编辑时重新查询数据，并更新对应的值
    const { record } = this.state;
    if (!id) {
      message.error('产品id不存在！');
      return;
    }
    this.props.dispatch({
      type: 'ProductManageM/queryProductInfo',
      payload: {
        id,
        type: 'view',
      },
      callback: (data) => {
        if (data && data[0]) {
          let temp = data[0].baseInfo || {};
          const obj = {
            productType: temp.type,
            startDate: temp.startDate ? temp.startDate : undefined,
            endDate: temp.endDate ? temp.endDate : undefined,
            productName: data.name || record.productName,
            productCode: data.code || record.productCode,
          };
          this.setState({
            record: {
              raisedMoney: record.raisedMoney,
              expectedRate: record.expectedRate,
              maatProductId: record.maatProductId,
              costRate: record.costRate,
              reward: record.reward,
              ...obj,
            },
            isVisible: true,
          });
        }
      },
    });
  };

  // 点击取消
  handleCancel = () => {
    this.setState({
      isVisible: false,
      isEdit: false, //编辑状态改为false
      id: undefined, //编辑时的id
      record: {}, //编辑行的数据
    });
  };
  // 新增编辑modal框
  showModal = () => {
    const { isVisible, record, isEdit } = this.state;
    const { loading } = this.props;
    const text = isEdit ? '编辑' : '新增';
    const newProps = { visible: isVisible, title: `${text}`, width: 1100 };
    return (
      <div>
        <ModalC {...newProps} onOk={this.handleOk} onCancel={this.handleCancel} confirmLoading={loading.effects['ProductManageM/addAndEdit'] === true}>
          <MyModal
            onRef={(ref) => (this.child = ref)} // 父组件对本组件的引用
            isEdit={isEdit} // 修改或编辑
            defaultData={record} // 修改时回填的数据
          />
        </ModalC>
      </div>
    );
  };

  // 编辑
  editData = (record) => {
    this.setState(
      {
        id: record.productId,
        record: record,
        isEdit: true,
      },
      () => {
        this.queryProductInfo(record.maatProductId);
      },
    );
  };

  // 删除
  deleteData = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ProductManageM/deleteData',
      payload: { id: record.productId },
      callback: () => {
        this.getTableData();
      },
    });
  };

  // 新增
  handleAdd = () => {
    this.setState({
      isEdit: false,
      isVisible: true,
    });
  };

  // 改变columns的样式
  changeColumns = (columns) => {
    let data = columns;
    if (data && data.length) {
      if (data[data.length - 1].title !== '操作') {
        data.push({
          title: '操作',
          type: 'operate',
          operates: [
            { title: '编辑', onClick: (record) => this.editData(record) },
            { title: '删除', onClick: (record) => this.deleteData(record) },
          ],
        });
      }
      data.map((item) => {
        if (item.key == 'raisedMoney') {
          item.type = 'money';
        }
        if (item.key == 'createDate') {
          item.type = 'date';
        }

        if (item.key == 'expectedRate' || item.key == 'costRate' || item.key == 'reward' || item.key == 'actualRate') {
          item.type = 'rate';
          item.toFixed = 4;
        }
      });
    }
    return data;
  };
  handleChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState({
      currentPage: current,
      numInPage: pageSize,
    });
  };
  onQuery = (e) => {
    //点击快捷按钮
    this.setState(
      {
        isNegativeCash: e,
      },
      () => {
        if (!this.state.seriesProductId) return;
        this.getTableData();
      },
    );
  };
  showTable = () => {
    const {
      ProductManageM: { tableData },
      loading,
    } = this.props;
    const newColumns = this.changeColumns(tableData.columns);
    const dataSource = tableData.dataSource;
    return (
      <div>
        <div style={{ margin: '10px 0' }}>
          <PrimaryC title='新增产品' onClick={this.handleAdd} />
          <div style={{ display: 'inline-block', marginLeft: '10px' }}>
            <QuickQueryC
              dataSource={[
                { value: '0', title: '全部' },
                { value: '1', title: '负现金' },
              ]}
              initialValue='0'
              onChange={this.onQuery}
            />
          </div>
          <div className={style.tips}>
            提示：<span className={style.bg}></span>这个橙色代表“负现金产品”
          </div>
        </div>
        <TableC
          dataSource={dataSource}
          columns={newColumns}
          loading={loading.effects['ProductManageM/getTableData'] == true}
          current={this.state.currentPage}
          pageSize={this.state.numInPage}
          onChange={this.handleChange}
          rowKey='productId'
          rowClassName={(record) => {
            return record.negativeCash == 1 ? style.row_select : '';
          }}
          scroll={{ x: 'max-content' }}
        />
      </div>
    );
  };
  render() {
    const { seriesProductId } = this.state;
    return (
      <div>
        <div>
          <SecondHeaderC title={`产品详情 (${this.props.listName || '--'})`} />
        </div>
        {seriesProductId ? (
          this.showTable()
        ) : (
          <div style={{ marginTop: '10px' }}>
            <NoQueryC title='请双击上方表格的某一行，查询对应产品信息' />
          </div>
        )}
        {this.state.isVisible && this.showModal()}
      </div>
    );
  }
}
